<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/common.php';

use Workerman\Worker;
use \Workerman\Connection\AsyncTcpConnection;


try{
    $config = get_config();
}catch(\Exception $e){
    echo "error:{$e}\n";
}

if(isset($config['nat_list'])){

    clean_temp_cient();

    foreach ($config['nat_list'] as $n_key => $n_value) {
        $unique_key = $n_key;
        $nat_client_list['nat_client_worker_'.$n_key] = build_client_for_win_woker($n_value,$n_key);
    }
    $cmd = build_cmd();
    echo system($cmd);
}else{
    $worker = build_client_woker($config);
}

Worker::runAll();


function build_client_for_win_woker($config,$key)
{
    $tpl_code = file_get_contents(__DIR__."/temp_client_for_win/tpl.php");
    $tpl_code = str_replace('#config#',json_encode($config),$tpl_code);
    file_put_contents(__DIR__."/temp_client_for_win/temp_client_".$key.".php",$tpl_code);
}

function clean_temp_cient()
{
    $temp_dir_list = scandir(__DIR__."/temp_client_for_win/");

    foreach ($temp_dir_list as $t_key => $t_value) {
        if($t_value != '.' && $t_value != '..' && $t_value != 'tpl.php' ){
            unlink(__DIR__."/temp_client_for_win/".$t_value);
        }
    }

}

function build_cmd()
{
    $cmd = "php ";
    $temp_dir_list = scandir(__DIR__."/temp_client_for_win/");

    foreach ($temp_dir_list as $t_key => $t_value) {
        if($t_value != '.' && $t_value != '..' && $t_value != 'tpl.php' ){
            $cmd .= __DIR__."/temp_client_for_win/".$t_value." ";
        }
    }

    return $cmd;
}